package com.syj.collect.fragment;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.syj.collect.entry.KeyvalueBean;
import com.syj.collect.entry.OcrBean;
import com.syj.collect.entry.StationDetailBean;
import com.syj.collect.entry.StationPointBean;
import com.syj.collect.entry.TaskBean;
import com.syj.collect.entry.UserInfoBean;
import com.syj.collect.http.ApiServise;
import com.syj.collect.listnner.MyItemListener;
import com.syj.collect.listnner.MyLocationListener;
import com.syj.collect.Present.CHomePresent;
import com.syj.collect.adapter.AdapterWaterAnalyze;
import com.syj.collect.adapter.MyPicAdapter;
import com.syj.collect.adapter.TagAdapter;
import com.syj.collect.app.MyApplication;
import com.syj.collect.app.R;
import com.syj.collect.base.BaseFragment;
import com.syj.collect.entry.TagAdapterData;
import com.syj.collect.entry.WaterColorBean;
import com.syj.collect.model.MyTaskActivity;
import com.syj.collect.utils.FileUtil;
import com.syj.collect.utils.Glide4Engine;
import com.syj.collect.utils.HttpUtils;
import com.syj.collect.utils.LogUtils;
import com.syj.collect.utils.RecognizeService;
import com.syj.collect.utils.SPUtil;
import com.syj.collect.utils.SensorEventHelper;
import com.syj.collect.utils.ToastMgr;
import com.syj.collect.view.CHomeView;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static android.app.Activity.RESULT_OK;

public class HomeFragment extends BaseFragment implements View.OnClickListener, MyLocationListener, CHomeView, MyItemListener {
    private static final int REQUEST_CODE_CUSTOM = 132;
    private static final int REQUEST_CODE_GENERAL = 105;
    private static final int REQUEST_CODE_NUMBERS = 126;
    private static final int REQUEST_CODE_ACCURATE_BASIC = 107;
    private int intheight;
    private boolean Show = true;
    private LinearLayout mainView;
    private MapView mapView;
    private AMap aMap;
    private TextView addrTv;
    private RxPermissions rxPermissions;
    private AMapLocationClient mlocationClient;
    private boolean isFirst = false;

    public static final String LOCATION_MARKER_FLAG = "mylocation";
    private Marker mLocMarker;
    private Marker lastMarker;
    private SensorEventHelper mSensorHelper;
    private CHomePresent present;
    private TagAdapter tagAnalyze;
    private TextView colorBlock;
    private Spinner spinner;
    private MyPicAdapter picAdapter;
    private ImageView headimg;
    private Button submit;
    private TextView save, title;
    private AdapterWaterAnalyze adapterWaterAnalyze;
    private EditText supplyMsg, fixMsg;
    private WaterColorBean.WaterColor selectSpinner = null;
    private LinearLayout infoWindow;
    private Marker curuntMarker;//当前点击的marker
    private String curuntFixmsg = "";//当前固定信息
    private int mYpos = 0;

    private TextView infoWindow_title, custom_info_tv, custom_info_tv1, custom_info_tv2, custom_info_tv3;
    private TextView emgency_tasknum, emgency_tasknum1;
    private List<StationPointBean.StationPoint> makerData = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.fargment_home;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initAccessTokenWithAkSk();
        present = new CHomePresent();
        present.attach(this);
        rxPermissions = new RxPermissions(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        rootView.findViewById(R.id.show_map).setOnClickListener(this);
        infoWindow = rootView.findViewById(R.id.mapcustomwindow);
        mapView = (MapView) rootView.findViewById(R.id.map);
        title = (TextView) rootView.findViewById(R.id.f_home_title);
        addrTv = (TextView) rootView.findViewById(R.id.home_addr_tv);
        emgency_tasknum = (TextView) rootView.findViewById(R.id.emgency_tasknum);
        emgency_tasknum1 = (TextView) rootView.findViewById(R.id.emgency_tasknum1);
        rootView.findViewById(R.id.task_linear).setOnClickListener(this);

        infoWindow_title = (TextView) rootView.findViewById(R.id.statitle);
        custom_info_tv = (TextView) rootView.findViewById(R.id.custom_info_tv);
        custom_info_tv1 = (TextView) rootView.findViewById(R.id.custom_info_tv1);
        custom_info_tv2 = (TextView) rootView.findViewById(R.id.custom_info_tv2);
        custom_info_tv3 = (TextView) rootView.findViewById(R.id.custom_info_tv3);
        colorBlock = (TextView) rootView.findViewById(R.id.colorblock);
        spinner = (Spinner) rootView.findViewById(R.id.mspinner);
        save = (TextView) rootView.findViewById(R.id.msave);
        save.setVisibility(View.VISIBLE);
        submit = (Button) rootView.findViewById(R.id.f_submit);
        submit.setVisibility(View.VISIBLE);
        headimg = (ImageView) rootView.findViewById(R.id.f_home_img);
        supplyMsg = (EditText) rootView.findViewById(R.id.supplymsg);
        fixMsg = (EditText) rootView.findViewById(R.id.fixmsg);
        submit.setOnClickListener(this);
        save.setOnClickListener(this);
        String value = SPUtil.getPrefString("userInfo", "");
        Gson json = new Gson();
        UserInfoBean.UserInfo result = json.fromJson(value, UserInfoBean.UserInfo.class);
        Glide.with(this).load(HttpUtils.ImgURL + result.getIconUrl()).apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.mipmap.moren)).into(headimg);
        rootView.findViewById(R.id.getaddr).setOnClickListener(this);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();

        //改变地图缩放的位子
        UiSettings uiSettings = aMap.getUiSettings();
        //uiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);
        uiSettings.setZoomControlsEnabled(false);

        mSensorHelper = new SensorEventHelper(getContext());
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }

        aMap.setLocationSource(new LocationSource() {
            @Override
            public void activate(OnLocationChangedListener onLocationChangedListener) {
                mlocationClient = ((MyApplication) getActivity().getApplication()).getSetLoctionClient(HomeFragment.this::onmLocationChanged);

            }

            @Override
            public void deactivate() {
                mlocationClient.stopLocation();
            }
        });// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setRotateGesturesEnabled(false);
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        //setupLocationStyle();
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (!isEmpty(marker.getTitle())) {
                    infoWindow_title.setText(marker.getTitle() + "");
                    if (infoWindow.isShown() && marker.equals(curuntMarker)) {
                        //marker.hideInfoWindow();
                        infoWindow.setVisibility(View.GONE);
                        changeMaker(marker, false);

                    } else {
                        // marker.showInfoWindow();
                        infoWindow.setVisibility(View.VISIBLE);

                        curuntMarker = marker;
//                        Log.e("oooooo1", curuntMarker.getObject() + " v " + curuntMarker.getTitle());
                        changeMaker(marker, true);
                        present.getStationData(marker);

                    }
                    lastMarker = marker;
                    fixMsg.setText(marker.getObject() == null ? "" : marker.getObject() + "");
                    return true;
                }
                return false;
            }
        });

        LinearLayout mapView = (LinearLayout) rootView.findViewById(R.id.map_view);
        mainView = (LinearLayout) rootView.findViewById(R.id.collect_main);
        RecyclerView picrec = (RecyclerView) rootView.findViewById(R.id.com_rec);
        picrec.setLayoutManager(new GridLayoutManager(rootView.getContext(), 3));
        picAdapter = new MyPicAdapter();
        picAdapter.setonClick(new MyItemListener() {
            @Override
            public void onmListenner(int pos) {

                rxPermissions.requestEachCombined(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Observer<Permission>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Permission permission) {
                                if (permission.granted) {
                                    //成功获取权限
                                    Matisse.from(getActivity())
                                            .choose(MimeType.ofImage())
                                            .capture(true)
                                            .countable(true)
                                            .captureStrategy(new CaptureStrategy(true, "com.syj.collect.app"))
                                            .maxSelectable(3)
                                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                            .thumbnailScale(0.85f)
                                            .imageEngine(new Glide4Engine())//Glide4
                                            .forResult(1);

                                } else if (permission.shouldShowRequestPermissionRationale) {
                                    //用户拒绝权限
                                    ToastMgr.builder.display("您禁止了拍照权限");
                                } else {
                                    //用户禁止权限勾选了不在提示
                                    Intent localIntent = new Intent();
                                    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                    localIntent.setData(Uri.fromParts("package", getActivity().getPackageName(), null));
                                    startActivity(localIntent);
//                                    LogUtils.i("用户禁止权限勾选了不在提示");
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });


            }
        });
        picrec.setAdapter(picAdapter);

        RecyclerView analyrec = (RecyclerView) rootView.findViewById(R.id.com_rec1);
        adapterWaterAnalyze = new AdapterWaterAnalyze(0);
        adapterWaterAnalyze.setonclik(this);
        analyrec.setLayoutManager(new GridLayoutManager(rootView.getContext(), 6));
        analyrec.setAdapter(adapterWaterAnalyze);

        // TODO: 2021/3/24


        RecyclerView tagRec = (RecyclerView) rootView.findViewById(R.id.com_rec2);

        tagAnalyze = new TagAdapter();
        FlexboxLayoutManager fLayout = new FlexboxLayoutManager(this.getContext());
        fLayout.setFlexWrap(FlexWrap.WRAP);
        fLayout.setFlexDirection(FlexDirection.ROW);
        fLayout.setAlignItems(AlignItems.STRETCH);
        fLayout.setJustifyContent(JustifyContent.FLEX_START);
        tagRec.setLayoutManager(fLayout);
        tagRec.setAdapter(tagAnalyze);
        // TODO: 2021/3/25


        //addrTv.setText(MyApplication.aAmps != null ? MyApplication.aAmps.getAddress() : "请手动点击右侧定位图标");
        mapView.post(new Runnable() {
            @Override
            public void run() {
                // int width = mapView.getMeasuredWidth();
                intheight = mapView.getMeasuredHeight();
//                Log.e("height", intheight + "");
            }
        });
        present.getStationList();
        present.getTagDate();
        present.getWaterColor();
        present.getTaskList1();
        // if (mlocationClient != null) mlocationClient.startLocation();
        return rootView;
    }

    private void initSpinner(List<WaterColorBean.WaterColor> list) {
        ArrayAdapter<WaterColorBean.WaterColor> adapter = new ArrayAdapter<WaterColorBean.WaterColor>(this.getContext(), android.R.layout.simple_spinner_item, list);
        //第三步：设置下拉列表下拉时的菜单样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        spinner.setAdapter(adapter);
        //第五步：添加监听器，为下拉列表设置事件的响应
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


                GradientDrawable myGrad = (GradientDrawable) colorBlock.getBackground();
                myGrad.setColor(Color.parseColor(list.get(position).getDescription()));


//                colorBlock.setBackgroundColor(Color.parseColor(list.get(position).getDescription()));
                selectSpinner = list.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.show_map) {

            setMargin(v, mainView);
        }
        if (v.getId() == R.id.getaddr) {
            if (mlocationClient != null) mlocationClient.startLocation();
            // Toast.makeText(getContext(), "为开发方便暂关闭定位", Toast.LENGTH_LONG).show();
        }
        if (v.getId() == R.id.msave) {
            //保存
            checkContent(true);
        }
        if (v.getId() == R.id.f_submit) {
            //提交

            checkContent(false);
        }
        if (v.getId() == R.id.task_linear) {
            Intent intent = new Intent(getContext(), MyTaskActivity.class);
            intent.putExtra("ttype", 2);
            getActivity().startActivity(intent);
        }
    }

    StringBuffer stringBuffer;

    private void checkContent(boolean issave) {
        List<TagAdapterData.WaterBean> select = tagAnalyze.getSelect();
        stringBuffer = new StringBuffer();
        for (int i = 0; i < select.size(); i++) {
            stringBuffer.append(select.get(i).getLabel());
            stringBuffer.append(";");
        }


//        Log.e("ooooo", tagAnalyze.getSelect().toString() + "66666666666666");
        if (adapterWaterAnalyze.getDate().get(0).getValue() <= 0) {
            Toast.makeText(getContext(), adapterWaterAnalyze.getDate().get(0).getKey() + "不能为0", Toast.LENGTH_LONG).show();
        } else if (adapterWaterAnalyze.getDate().get(1).getValue() <= 0) {
            Toast.makeText(getContext(), adapterWaterAnalyze.getDate().get(1).getKey() + "不能为0", Toast.LENGTH_LONG).show();

        } else if (adapterWaterAnalyze.getDate().get(2).getValue() <= 0) {
            Toast.makeText(getContext(), adapterWaterAnalyze.getDate().get(2).getKey() + "不能为0", Toast.LENGTH_LONG).show();

        } else if (adapterWaterAnalyze.getDate().get(3).getValue() <= 0) {
            Toast.makeText(getContext(), adapterWaterAnalyze.getDate().get(3).getKey() + "不能为0", Toast.LENGTH_LONG).show();

        } else if (adapterWaterAnalyze.getDate().get(4).getValue() <= 0) {
            Toast.makeText(getContext(), adapterWaterAnalyze.getDate().get(4).getKey() + "不能为0", Toast.LENGTH_LONG).show();

        } else if (picAdapter.getPicList().isEmpty()) {
            Toast.makeText(getContext(), "你还没有选择图片", Toast.LENGTH_LONG).show();
        } else if (isEmpty(fixMsg.getText().toString()) || isEmpty(supplyMsg.getText().toString())) {
            Toast.makeText(getContext(), "你还没有写描述或补充信息", Toast.LENGTH_LONG).show();
        } else if (selectSpinner == null) {
            Toast.makeText(getContext(), "你还没有选择水质色描述", Toast.LENGTH_LONG).show();
        } else if (tagAnalyze.getSelect().isEmpty()) {
            Toast.makeText(getContext(), "你还没有选择水质描述", Toast.LENGTH_LONG).show();
        } else if (curuntMarker == null || curuntMarker.getTitle() == null) {
            Toast.makeText(getContext(), "你还没有选择站点", Toast.LENGTH_LONG).show();
        } else {
//            Log.e("ooooo", curuntMarker.getTitle() + " " + curuntMarker.getObject());
//            present.upLoadFiles(issave, curuntMarker.getTitle() + "", picAdapter.getPicList(), adapterWaterAnalyze.getDate(), fixMsg.getText().toString(), supplyMsg.getText().toString(), selectSpinner);
            present.upLoadFiles(issave, curuntMarker.getTitle() + "", picAdapter.getPicList(), adapterWaterAnalyze.getDate(), stringBuffer.toString(), supplyMsg.getText().toString(), selectSpinner);

        }


    }


    public boolean isEmpty(String str) {
        if (str != "" && str != null && !str.isEmpty()) {
            return false;
        } else return true;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        OCR.getInstance(getContext()).release();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    public void setMargin(View view, View view1) {
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) view1.getLayoutParams();

        lp.setMargins(lp.leftMargin, Show ? 40 : intheight, lp.rightMargin, 0);
        Show = !Show;
        ((ImageView) view).setImageResource(Show ? R.mipmap.select_up : R.mipmap.select_down);
        view1.requestLayout();
    }


    @Override
    public void onmLocationChanged(AMapLocation amapLocation) {

        if (amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {

                LatLng location = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                if (!isFirst) {
                    isFirst = true;
                    // addCircle(location, amapLocation.getAccuracy());//添加定位精度圆
                    //initMarkers(location);//添加定位图标
                    MarkerOptions option = new MarkerOptions();

                    //option.icon(BitmapDescriptorFactory.fromResource(R.drawable.xun_now_back));

                    option.icon(mergeThumbnailBitmap(getResources().getDrawable(R.drawable.xun_now_back), headimg.getDrawable()));
                    option.anchor(0.5f, 0.5f);
                    option.position(location);
                    mLocMarker = aMap.addMarker(option);
                    //mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
                } else {
                    //mCircle.setCenter(location);
                    //mCircle.setRadius(amapLocation.getAccuracy());
                    mLocMarker.setPosition(location);
                }
                addrTv.setText(amapLocation.getAddress());
                StationPointBean.StationPoint oo = new StationPointBean.StationPoint();
                oo.setLat(mLocMarker.getPosition().latitude);
                oo.setLon(mLocMarker.getPosition().longitude);
                if (!makerData.isEmpty() && makerData.contains(oo)) {
                    mLocMarker.setTitle(makerData.get(makerData.indexOf(oo)).getStationCode());
                    title.setText("采集  (" + mLocMarker.getTitle() + ")");
                } else {
                    mLocMarker.setTitle("");
                    title.setText("采集");
                }


                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
//                Log.e("AmapErr", errText);
                addrTv.setText((errText));
                title.setText("采集");
            }
        }


    }


    public void initMarkers(List<StationPointBean.StationPoint> data) {
        makerData.clear();
        makerData.addAll(data);
      /*  if (mLocMarker != null) {
            return;
        }*/
        for (int i = 0; i < data.size(); i++) {
            if (mLocMarker != null) {
                LatLng lan = new LatLng(data.get(i).getLat(), data.get(i).getLon());

                if (mLocMarker.getPosition().equals(lan)) {
                    curuntFixmsg = isEmpty(data.get(i).getDescription()) ? "" : data.get(i).getDescription() + "";
                    fixMsg.setText(curuntFixmsg);
                    fixMsg.setEnabled(false);
                    mLocMarker.setTitle(data.get(i).getStationCode());
                    title.setText("采集  (" + data.get(i).getStationCode() + ")");

                }
            }
            MarkerOptions option = new MarkerOptions();

            //option.icon(BitmapDescriptorFactory.fromResource(R.drawable.xun_now_back));
            option.icon(BitmapDescriptorFactory.fromResource(data.get(i).getGrade().equals("2") ? R.drawable.xun_red : R.drawable.xun_blue));
            option.anchor(0.5f, 0.5f);
            option.position(new LatLng(data.get(i).getLat(), data.get(i).getLon()));
            Marker maker = aMap.addMarker(option);

            maker.setObject(data.get(i).getDescription());
            maker.setTitle(data.get(i).getStationCode());

            changeMaker(maker, false);
        }


        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(data.get(0).getLat(), data.get(0).getLon()), 16));

    }

    private void changeMaker(Marker maker, boolean isLarger) {
        float from = isLarger ? 1f : 1.25f;
        float to = isLarger ? 1.25f : 1f;
        if (lastMarker != null) {
            Animation animation = new ScaleAnimation(to, from, to, from);
            long duration = 500L;
            animation.setDuration(duration);
            animation.setInterpolator(new LinearInterpolator());
            animation.setFillMode(0);
            animation.setRepeatCount(0);
            lastMarker.setAnimation(animation);
            lastMarker.startAnimation();
        }

        Animation animation = new ScaleAnimation(from, to, from, to);
        long duration = 500L;
        animation.setDuration(duration);
        animation.setInterpolator(new LinearInterpolator());
        animation.setFillMode(0);
        animation.setRepeatCount(0);
        maker.setAnimation(animation);
        maker.startAnimation();
    }


    @Override
    public void initSuccess(String str) {
        Toast.makeText(getContext(), str, Toast.LENGTH_LONG).show();
    }

    @Override
    public void initSuccess(List<StationDetailBean.StationDetai> str, Marker marker) {
        if (!str.isEmpty()) {
            custom_info_tv.setText(str.get(0).getCod() + "");
            custom_info_tv1.setText(str.get(0).getNh3() + "");
            custom_info_tv2.setText(str.get(0).getTn() + "");
            custom_info_tv3.setText(str.get(0).getAnionic() + "");

        } else {
            Toast.makeText(getContext(), "此站点暂时没有有效数据", Toast.LENGTH_LONG).show();
            custom_info_tv.setText("");
            custom_info_tv1.setText("");
            custom_info_tv2.setText("");
            custom_info_tv3.setText("");
        }

    }


    @Override
    public void initTagSuccess(List<TagAdapterData.WaterBean> data) {
        tagAnalyze.upDate(data);
    }

    @Override
    public void initColorSuccess(List<WaterColorBean.WaterColor> str) {
        initSpinner(str);
    }

    @Override
    public void initgetStationSuccess(List<StationPointBean.StationPoint> str) {

        initMarkers(str);
        if (curuntFixmsg != null && curuntFixmsg != "" && !curuntFixmsg.isEmpty()) {

        }
    }

    @Override
    public void initFail(String str) {

    }

    @Override
    public void initTaskSuccess(int totalCount, List<TaskBean.DataBean.ListBean> list) {
        emgency_tasknum.setText(totalCount + "");
        emgency_tasknum1.setText(totalCount + "");
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        Log.e("results", requestCode + "   " + resultCode + data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            List mSelected = Matisse.obtainResult(data);
//            Log.e("results", requestCode + mSelected.get(0).toString());
            picAdapter.upDate(getContext(), mSelected);
        }
        // 识别成功回调，自定义模板
 /*       if (requestCode == REQUEST_CODE_CUSTOM && resultCode == Activity.RESULT_OK) {
            RecognizeService.recCustom(getContext(), FileUtil.getSaveFile(getContext()).getAbsolutePath(), new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {

                        }
                    }
            );


        }*/


        // 识别成功回调，数字
        if (requestCode == REQUEST_CODE_NUMBERS && resultCode == Activity.RESULT_OK) {
            RecognizeService.recNumbers(getContext(), FileUtil.getSaveFile(getContext()).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
//                            Log.e("results", result);
                            float ff = 0;
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                JSONArray array = jsonObject.getJSONArray("words_result");
                                for (int i = 0; i < array.length(); i++) {
                                    ff = (float) array.getJSONObject(i).getDouble("words");
                                    break;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                            if (ff > 0) {
//                                Log.e("resultsm", ff + "");
                                Toast.makeText(getContext(), "当前识别到数字:  " + ff, Toast.LENGTH_LONG).show();
                                adapterWaterAnalyze.setmDate(mYpos, ff > 10 ? ff / 100 : ff);
                            } else {
                                Toast.makeText(getContext(), "当前未识别到有效数字", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
        }

        // 识别成功回调，通用文字识别（含位置信息）
        if (requestCode == REQUEST_CODE_ACCURATE_BASIC && resultCode == Activity.RESULT_OK) {
            RecognizeService.recGeneral(getContext(), FileUtil.getSaveFile(getContext()).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
//                            Log.e("results", result);
                            Gson gson = new Gson();
                            OcrBean gbean = gson.fromJson(result, OcrBean.class);
                            Float ff = 0f;
                            if (gbean.getWords_result_num() != 0) {
                                for (int o = 0; o < gbean.getWords_result().size(); o++) {
                                    float aa = 0f;
                                    try {
                                        aa = Float.parseFloat(gbean.getWords_result().get(o).getWords());
                                    } catch (Exception e) {
                                        aa = 0f;
                                    }
                                    if (aa > 0) {
                                        ff = aa;
                                        break;
                                    }
                                }
                            }
                            if (ff > 0) {
//                                Log.e("resultsm", ff + "");
                                Toast.makeText(getContext(), "当前识别到数字:  " + ff, Toast.LENGTH_LONG).show();
                                adapterWaterAnalyze.setmDate(mYpos, ff > 10 ? ff / 100 : ff);
                            } else {
                                Toast.makeText(getContext(), "当前未识别到有效数字", Toast.LENGTH_LONG).show();
                            }
                            List<KeyvalueBean> nbean = adapterWaterAnalyze.getDate();


                        }
                    });
        }
    }

    public void startmActivity() {
       /* //自定义
       Intent intent = new Intent(getActivity(), CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(getContext()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        startActivityForResult(intent, REQUEST_CODE_CUSTOM);*/
        Intent intent = new Intent(getActivity(), CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(getContext()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        startActivityForResult(intent, REQUEST_CODE_NUMBERS);
    }

    private void initAccessTokenWithAkSk() {
        OCR.getInstance(getContext()).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
//                Log.e("results token", token);
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                //alertText("AK，SK方式获取token失败", error.getMessage());
            }
            //}, getApplicationContext(),  "请填入您的AK", "请填入您的SK");
        }, getContext().getApplicationContext(), ApiServise.OCRAK, ApiServise.OCRSK);
    }

    @Override
    public void onmListenner(int pos) {
        if (pos != 5) {
            mYpos = pos;
        } else {

        }
        startmActivity();
    }

    private BitmapDescriptor mergeThumbnailBitmap(Drawable drawable, Drawable secondBitmap1) {
        //以其中一张图片的大小作为画布的大小，或者也可以自己自定义
        BitmapDrawable bd = (BitmapDrawable) drawable;
        Bitmap firstBitmap = bd.getBitmap();

        BitmapDrawable bd1 = (BitmapDrawable) secondBitmap1;
        Bitmap secondBitmap = bd1.getBitmap();
        Bitmap bitmap = Bitmap.createBitmap(firstBitmap.getWidth(), firstBitmap
                .getHeight(), firstBitmap.getConfig());
        //生成画布
        Canvas canvas = new Canvas(bitmap);
        //因为我传入的secondBitmap的大小是不固定的，所以我要将传来的secondBitmap调整到和画布一样的大小
        float w = firstBitmap.getWidth();
        float h = firstBitmap.getHeight();
        Matrix m = new Matrix();
        //确定secondBitmap大小比例
        m.setScale(w / (secondBitmap.getWidth() + 20), w / (secondBitmap.getHeight() + 20));
        Paint paint = new Paint();

        //给画笔设定透明值，想将哪个图片进行透明化，就将画笔用到那张图片上
        //paint.setAlpha(150);

        canvas.drawBitmap(firstBitmap, 0, 0, null);
        Bitmap newBitmap = Bitmap.createBitmap(secondBitmap, 0, 0, secondBitmap.getWidth(), secondBitmap.getHeight(), m, true);
        int ll = (int) (w - newBitmap.getWidth()) / 2;
        //canvas.drawBitmap(secondBitmap, m, paint);
        Rect mDestRect = new Rect(ll, ll, (int) (ll + newBitmap.getWidth()), (int) (ll + newBitmap.getHeight()));
        Rect mSrcRect = new Rect(0, 0, newBitmap.getWidth(), newBitmap.getHeight());
        canvas.drawBitmap(newBitmap, mSrcRect, mDestRect, paint);

        return BitmapDescriptorFactory.fromBitmap(bitmap);
    }

}
